/*
 *  Copyright 2011 yura.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.vcforms.dtseditor;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import jsyntaxpane.DefaultSyntaxKit;
import org.opu.vcforms.vcapi.domain.VcTextTemplate;

/**
 *
 * @author yura
 */
public class TemplatePanel extends javax.swing.JPanel {

    static {
        DefaultSyntaxKit.initKit();
        DefaultSyntaxKit.getContentTypes();
    }

    public static final String EDIT_NONE = "NONE";
    public static final String EDIT_XML = "XML";
    public static final String EDIT_DOCX_XML = "DOCX[xml]";

    private javax.swing.JPanel contentPanel;
    private javax.swing.JComboBox docTypeCb;
    private javax.swing.JLabel docTypeLbl;
    private javax.swing.JComboBox editModeCb;
    private javax.swing.JLabel editModeLbl;
    private javax.swing.JFormattedTextField fdataFtTf;
    private javax.swing.JLabel fdateLbl;
    private javax.swing.JLabel fnameLbl;
    private javax.swing.JTextField fnameTf;
    private javax.swing.JFormattedTextField idFtTf;
    private javax.swing.JLabel idLbl;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton refresh;
    private javax.swing.JButton save;
    private javax.swing.JButton validate;
    private javax.swing.JButton upload;

    private HelpPanel helpPanel;
    private ContentEditor contentEditor;
    private byte[] contentValue;

    public TemplatePanel(HelpPanel helpPanel) {
        this.helpPanel = helpPanel;
        initComponents();
    }

    private void initComponents() {

        idLbl = new javax.swing.JLabel();
        docTypeLbl = new javax.swing.JLabel();
        fnameLbl = new javax.swing.JLabel();
        fdateLbl = new javax.swing.JLabel();
        contentPanel = new javax.swing.JPanel();
        editModeLbl = new javax.swing.JLabel();
        idFtTf = new javax.swing.JFormattedTextField();
        docTypeCb = new javax.swing.JComboBox();
        fnameTf = new javax.swing.JTextField();
        fdataFtTf = new javax.swing.JFormattedTextField();
        editModeCb = new javax.swing.JComboBox();
        jPanel1 = new javax.swing.JPanel(new java.awt.BorderLayout());
        save = Util.initBtn(new javax.swing.JButton());
        refresh = Util.initBtn(new javax.swing.JButton());
        upload = Util.initBtn(new javax.swing.JButton());
        validate = Util.initBtn(new javax.swing.JButton());

        contentValue = new byte[0];

        idLbl.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        idLbl.setText("Identifier:");
        idLbl.setToolTipText("(-1) default value: use auto generated value of database");

        docTypeLbl.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        docTypeLbl.setText("Document type:");

        fnameLbl.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        fnameLbl.setText("File name:");

        fdateLbl.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        fdateLbl.setText("File date:");

        contentPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("File content:"));
        contentPanel.setLayout(new java.awt.BorderLayout());

        editModeLbl.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        editModeLbl.setText("Edit mode:");

        idFtTf.setText("-1");
        idFtTf.setToolTipText("(-1) default value: use auto generated value of database");

        docTypeCb.setModel(new javax.swing.DefaultComboBoxModel(new DocumentType[] {
            new DocumentType('-', "NONE"),
            new DocumentType('D', "Sample to fill (D)"),
            new DocumentType('T', "XLS/DOC template (T)"),
            new DocumentType('X', "XML template (X)") }));
        docTypeCb.setSelectedIndex(0);
        docTypeCb.addActionListener(new ActionListener() {

            @Override public void actionPerformed(ActionEvent e) {
                try {
                    if (((DocumentType) docTypeCb.getSelectedItem()).getType() == 'X') {
                        editModeCb.setSelectedIndex(1);
                    }
                } catch (Exception ex) {
                    System.err.println("docTypeCb value change: " + ex);
                }
            }
        });

        editModeCb.setModel(new javax.swing.DefaultComboBoxModel(new String[] {
                EDIT_NONE, EDIT_XML, EDIT_DOCX_XML}));
        editModeCb.setSelectedIndex(0);
        editModeCb.addActionListener(new ActionListener() {

            @Override public void actionPerformed(ActionEvent e) {
                refreshEditor();
            }
        });

        save.setText("Save");
        save.setToolTipText("Save changes in to database");

        refresh.setText("Refresh");
        refresh.setToolTipText("Get data from database");

        validate.setText("Validate");
        validate.setToolTipText("Get data from database and try to validate it");

        upload.setText("Upload");
        validate.setToolTipText("Upload content file");

        javax.swing.Box v = javax.swing.Box.createVerticalBox();
        v.add(save);
        v.add(javax.swing.Box.createVerticalStrut(5));
        v.add(refresh);
        v.add(javax.swing.Box.createVerticalStrut(5));
        v.add(validate);
        v.add(javax.swing.Box.createVerticalStrut(5));
        v.add(upload);
        v.add(javax.swing.Box.createVerticalGlue());

        javax.swing.JPanel p = new javax.swing.JPanel(new java.awt.BorderLayout());
        p.add(v, java.awt.BorderLayout.EAST);

        javax.swing.Box h = javax.swing.Box.createHorizontalBox();
        h.add(javax.swing.Box.createHorizontalGlue());
        h.add(p);
        h.add(javax.swing.Box.createHorizontalStrut(5));

        jPanel1.add(h);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(editModeLbl, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(docTypeLbl, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(idLbl, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(fnameLbl, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(fdateLbl, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(idFtTf)
                    .addComponent(docTypeCb, 0, 142, Short.MAX_VALUE)
                    .addComponent(fdataFtTf)
                    .addComponent(editModeCb, 0, 143, Short.MAX_VALUE)
                    .addComponent(fnameTf))
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
            .addComponent(contentPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(idLbl)
                            .addComponent(idFtTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(docTypeLbl)
                            .addComponent(docTypeCb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(fnameLbl)
                            .addComponent(fnameTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(fdateLbl)
                            .addComponent(fdataFtTf, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(editModeLbl)
                            .addComponent(editModeCb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(22, 22, 22)
                .addComponent(contentPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }

    public void setVcTextTemplate(VcTextTemplate template){
        editModeCb.setSelectedIndex(0);
        idFtTf.setValue(template.getId() != null? template.getId(): new Integer(-1));
        contentValue = template.getFileContent();
        setDocType(template.getDocType());
        fnameTf.setText(String.valueOf(template.getFileName()));
        fdataFtTf.setText(template.getFileDate() != null? template.getFileDate(): "");
    }

    public VcTextTemplate getVcTextTemplate(){
        VcTextTemplate template = new VcTextTemplate();

        if (Integer.parseInt(idFtTf.getText()) != -1){
            template.setId((Integer) idFtTf.getValue());
        }

        template.setDocType(getDocType());
        template.setFileName(fnameTf.getText());

        if (contentEditor != null){
            template.setFileContent(contentEditor.getContent());
        } else {
            JOptionPane.showMessageDialog(null, "Data not modifieded",
                    "Data not modifieded", JOptionPane.WARNING_MESSAGE);
            template.setFileContent(contentValue);
        }
        template.setFileDate(!fdataFtTf.getText().isEmpty()? fdataFtTf.getText(): null);

        return template;
    }

    public Character getDocType(){
        return ((DocumentType) docTypeCb.getSelectedItem()).getType();
    }

    public void setDocType(Character ch){
        if (ch == null){
            return;
        }

        for(int i = 0; i < docTypeCb.getItemCount(); i++){
            DocumentType item = (DocumentType) docTypeCb.getItemAt(i);
            if (ch.equals(item.getType())){
                docTypeCb.setSelectedIndex(i);
                return;
            }
        }

        System.err.println("Wrong document type '" + ch + "'");
    }

    public javax.swing.JButton getRefresh() {
        return refresh;
    }

    public javax.swing.JButton getSave() {
        return save;
    }

    public javax.swing.JButton getValidate() {
        return validate;
    }

    public javax.swing.JButton getUpload() {
        return upload;
    }

    public void setContent(byte[] data){
        contentValue = data;
        refreshEditor();
    }

    /**
     * if docTypeCb have selected value open editor for it
     */
    public void refreshEditor(){
        String value = (String) editModeCb.getSelectedItem();
        contentEditor = null;
        contentPanel.removeAll();
        if (EDIT_XML.equals(value)){
            contentEditor = new XMLContentEditor(helpPanel, contentValue);
            contentPanel.add(contentEditor.asPanel());
        } else if (EDIT_DOCX_XML.equals(value)){
            try {
                contentEditor = new DocxXmlContentEditor(helpPanel, contentValue);
                contentPanel.add(contentEditor.asPanel());
            } catch (Exception ex) {
                Util.niceEx(ex, "Archive is corrupted", "Archive is corrupted:\n");
            }
        }

        revalidate();
        repaint();
    }
}

